
chrome.runtime.onMessage.addListener(async (msg, sender) => {
    console.log(msg)
    getSizeLimit(msg,0);
})


function getSizeLimit(msg,offset){

    if(!msg.data.item.category_id){
         console.log('msg error');
        return;
    }

    var dataRequest = {};
    var filter={};
    var categories = [];
    categories.push(msg.data.item.category_id+"");
    filter.stock='any_stock'
    filter.categories = categories;
    dataRequest.filter = filter;
    var sort = {};
    sort.key = "sum_rating";
    dataRequest.sort = sort;
    dataRequest.limit ="50";
    dataRequest.offset =offset;

     $.ajax({
        url: 'https://seller.ozon.ru/api/site/seller-analytics/what_to_sell/data/v3',
　　　　 type: 'POST',
        data:JSON.stringify(dataRequest),
        processData: false,
        contentType: 'application/json',
        headers: {
            'X-O3-App-Name': 'seller-ui',
            'X-O3-Company-Id': '1458518',
            'X-O3-Language': 'zh-Hans',
            'X-O3-Page-Type': 'what-to-sel'
          },
        xhrFields: {
            withCredentials: true // 这里设置了withCredentials
        },
        success: function(data) {
             console.log(data)
              totals = data.totals
              dataPro = data;
              dataPro.cate_id = msg.data.item.category_id;
               var type="upozonhotitem";
               var data = dataPro;
               chrome.runtime.sendMessage({ data: {type, data  }, close: false });
               if(offset==0){
                    var pageSize = 50;
                    // 计算总页数
                    var totalPages = Math.ceil(totals / pageSize);
                    // 遍历每一页
                    var time = 5000;
                    for (var page = 2; page <= totalPages; page++) {
                      (function(page) {
                        var newoffset = (page - 1) * pageSize;
                        console.log("page_" + page + " pageSize_" + pageSize + " newoffset_" + newoffset);
                        setTimeout(function() {
                          getSizeLimit(msg, newoffset);
                        }, time * (page - 1));
                      })(page);
                    }
               }

        },
        error: function(err) {
            console.error(err);
        }
    });
}


